<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use App\Model\Address;
use DB;

class CartController extends Controller
{

  // 购物车
	public function index()
	{

		$session_id = session()->getId();
		$user_id = session()->get('user')['id'];
		$getId = Redis::get($session_id);
		// dd($getId);
		if(!empty($user_id)){
			$uRedis = Redis::get($user_id);
		}
		if(!$user_id){
				if(!$getId){
					return view('Home/Cart');
				}else{
					$data = unserialize($getId);
					$money = 0;
					foreach ($data as $v) {
						$money += $v['shop_money']*$v['shop_num'];
					};
					return view('Home/Cart',['data' => $data,'user_id' => $user_id,'money' =>$money]);
				}
		}else{
			if(!$getId || !$uRedis){
				return view('Home/Cart');
			}else if($uRedis){
				// dd(123);
	  		$data = unserialize($uRedis);
				if(!$data){
					return view('Home/Cart');
				}
				$money = 0;
				foreach ($data as $v) {
					$money += $v['shop_money']*$v['shop_num'];
				}
			}else if(!$getId){
				$data = unserialize($uRedis);
				if(!$data){
					return view('Home/Cart');
				}
				$money = 0;
				foreach ($data as $v) {
					$money += $v['shop_money']*$v['shop_num'];
				}
			}
			return view('Home/Cart',['data' => $data,'user_id' => $user_id,'money' =>$money]);
		}
	}

	// 购买页
	public function Pay($id)
	{
		// dd($id);
		$address = Address::where('uid',$id)->get();
		$user_id = session()->get('user')['id'];
		if(!$user_id){
			return redirect('/login');
		}
		$getId = Redis::get($user_id);
    $data = unserialize($getId);
		$money = 0;
		foreach ($data as $v) {
			$money += $v['shop_money']*$v['shop_num'];
		}
		return view('Home/Pay',['money' =>$money, 'data' => $data, 'address' => $address]);
	}

	/**
	 * [payMoney 订单支付处理]
	 */
	 public function payMoney(Request $Request)
	 {
		 	$time = date('Y-m-d H:i:s');
		 $id = $Request->id;
		//  dd($id);
		 DB::transaction(function () use($id,$time) {
			 $order = DB::table('orders')->where('id',$id)->select('gid','uid','credits')->first();
			 $goods = DB::table('shop_goods')
			 						->join('shop_price','shop_goods.id','=','shop_price.gid')
									->select('shop_goods.goods_sales','shop_price.sales','shop_goods.goods_store','shop_price.store')
									->get();

			 $order_detail = DB::table('order_detail')->where('oid',$id)->select('*')->get();
			 DB::table('order_detail')
			 	 ->where('oid',$id)
				 ->update([
					 'evaluate_state'=>1
				 ]);
			 $num = 0;
			//  dd($order_detail->product_num);
			 foreach ($goods as $g) {
				 	foreach ($order_detail as $o) {
						$num +=	$o->product_num;
						$good_store = $g->store - $num;
				 		$price_stores = $g->store - $o->product_num;
						$gSales = $g->goods_sales + $num;
						$sales = $g->goods_sales + $o->product_num;

						DB::table('shop_goods')
							->where('id',$o->gid)
							->update([
								'goods_sales' =>$gSales,
								'goods_store'=>$good_store
							]);
						DB::table('shop_price')
							->where('gid',$o->gid)
							->update([
								'sales'=>$sales,
								'store'=>$price_stores
							]);


				 	}
			 }

			 $users = DB::table('users')->where('id',$order->uid)->select('id','total_intergral','surplus_intergral')->first();

			 $tIntergral = $users->total_intergral + $order->credits;
			 $sIntergral = $users->surplus_intergral + $order->credits;
			 $pay = DB::table('orders')
				->where('id',$id)
				->update([
					 'pay_state' => 1,
					 'pay_time' => $time,
					 'logistics'=>1
				 ]);
			DB::table('users')
				->where('id',$order->uid)
				->update([
					'total_intergral' =>$tIntergral,
					'surplus_intergral' => $sIntergral
				]);
		 });
			 return response()->json([
				 'code'=>2000,
				 'msg'=>'支付成功'
			 ]);

	 }




	// 改变商品数量
	public function changeNum(Request $Request)
	{
		$val = $Request->val;
		$id = $Request->id;
		// dd($id);
		$user_id = session()->get('user')['id'];
		$session = session()->getId();
		if(!$user_id){
			$getId = Redis::get($session);
			$arr = unserialize($getId);
			$arr[$id]['shop_num'] = $val;
			$redisSet = Redis::setex($session,604800,serialize($arr));
			$newArr = Redis::get($session);
			$arr = unserialize($newArr);
			$money = $arr[$id]['shop_num']*$arr[$id]['shop_money'];
			// dd($arr);
			$total = 0;
			foreach ($arr as $v) {
				// dd($v);
				$total += $v['shop_money']*$v['shop_num'];
			}
			return response()->json([
				'code'=>200,
				'money'=> $money,
				'total' => $total
			]);
		}else{
			$getId = Redis::get($user_id);
			$arr = unserialize($getId);
			// dd($arr);
			$arr[$id]['shop_num'] = $val;
			$redisSet = Redis::set($user_id,serialize($arr));
			$newArr = Redis::get($user_id);
			$arr = unserialize($newArr);
			$money = $arr[$id]['shop_num']*$arr[$id]['shop_money'];
			// dd($arr);
			$total = 0;
			foreach ($arr as $v) {
				// dd($v);
				$total += $v['shop_money']*$v['shop_num'];
			}
			return response()->json([
				'code'=>200,
				'money'=> $money,
				'total' => $total
			]);
		}
	}
	/**
	 * [doOrder 生成订单]
	 */
	public function doOrder(Request $request)
	{

			$aid = $request->aid;
			$address =  DB::table('address')->select()->where('id', $aid)->first();
			$man = $address->linkman;
			$uid = $address->uid;

			$phone = $address->telephone;
			$province = $address->province;
			$city = $address->city;
			$district = $address->town;
			$rDetail = $address->dec;
			$time = date('Y-m-d H:i:s');
			$user_id = session()->get('user')['id'];
			$Redis_id = Redis::get($user_id);
			$data = unserialize($Redis_id);

			$total = 0;
			foreach ($data as $v) {
				$total += $v['shop_money']*$v['shop_num'];
			}
			DB::transaction(function () use($uid,$man,$phone,$total,$time,$province,$city,$district,$rDetail,$data,$user_id) {
				DB::table('orders')->insert([
					'uid' => $uid,
					'linkman' => $man,
					'order_time'=> $time,
					'order_number' => time(),
					'telephone' => $phone,
					'total_money' => $total,
					'adderssname' => $province.$city.$district.$rDetail,
					'credits'=>$total,
				]);
				$lastOrder = DB::table('orders')
						->orderBy('id', 'desc')
						->first();
				$oid = $lastOrder->id;
				foreach ($data as $v) {
					 DB::table('order_detail')->insert([
						 'pid'=> $v['pid'],
						 'oid' => $oid,
						 'gid' => $v['shop_id'],
						 'goods_name' => $v['shop_name'],
						 'goods_pic' => $v['shop_pic'],
						 'unit_price' => $v['shop_money'],
						'product_num' => $v['shop_num'],
						'goods_name' => $v['shop_name'],
						'goods_specification'=> $v['shop_specification'],
						'single_intergral' => $v['single_intergral'],
					]);
				}
				Redis::del($user_id);

			});
			return response()->json([
				'code'=>2000,
				'msg'=>'下单成功'
			]);

	}




	// 加入购物车
	public function addCart(Request $Request)
	{

		$gid = $Request->id;
		$num = $Request->num;
		$memory = $Request->memory;
		$color = $Request->color;
		$price = $Request->price;

		$user_id = session()->get('user')['id'];
		$session = session()->getId();
		$getId = Redis::get($session);
		$arr = unserialize($getId);
		$pid = DB::table('shop_price')->where([ ['color',$color],['memory',$memory] ])->select('id')->first();
		$goods = DB::table('shop_goods')->where('id',$gid)->select('gname','pic')->first();
		$price = DB::table('shop_price')
							  ->where([
									['gid',$gid],
									['color',$color],
									['memory',$memory]
									])
								->select('*')
								->first();

		$data = [
				'shop_id' => $gid,
				'shop_name'=> $goods->gname,
				'single_intergral' => $price->price,
				'shop_specification'=> $color.$memory,
				'shop_pic' => $goods->pic,
				'shop_money'=> $price->price,
				'shop_num' => $num,
				'pid'=>$pid->id,
		];
		if(!$user_id){
				if(!$getId){
						$arr[$data['shop_id'].'+'.$price->id] = $data;

						$redisSet = Redis::setex($session,604800,serialize($arr));
				}
				// dd($arr);
				if(array_key_exists($data['shop_id'].'+'.$price->id,$arr)){
						$data['shop_num'] += $arr[$data['shop_id'].'+'.$price->id]['shop_num'];
						$arr[$data['shop_id'].'+'.$price->id] = $data;
				}else{
						$arr[$data['shop_id'].'+'.$price->id] = $data;
				}
						$redisSet = Redis::setex($session,604800,serialize($arr));
						$getId = Redis::get($session);
						$success = unserialize($getId);
		}else{
				// dd(1);
				$users = Redis::get($user_id);
				$userArr = unserialize($users);

				if(!$users){
						$arr[$data['shop_id'].'+'.$price->id] = $data;
						$redisSet = Redis::set($user_id,serialize($arr));
						// dd(123);

				}
				if(array_key_exists($data['shop_id'].'+'.$price->id,$userArr)){
						$data['shop_num'] += $userArr[$data['shop_id'].'+'.$price->id]['shop_num'];
						$userArr[$data['shop_id'].'+'.$price->id] = $data;
				}else{
						$userArr[$data['shop_id'].'+'.$price->id] = $data;
				};
						$redisSet = Redis::set($user_id,serialize($userArr));
		}

				return response()->json([
					'code'=> '2000',
					'msg'=> '成功加入购物车'
				]);
	}


	// 删除购物车商品
	public function deleteCart(Request $Request)
	{
		$id = $Request->rid;

		$user_id = session()->get('user')['id'];
		$session = session()->getId();
		$price = DB::table('shop_price')
							 ->where('gid',$id)
							 ->select('id','stores','color')
							 ->get();

		if(!$user_id){
			$getId = Redis::get($session);
			$arr = unserialize($getId);

			unset($arr[$id]);
			$redisSet = Redis::setex($session,604800,serialize($arr));
			$getArr = Redis::get($session);
			$success = unserialize($getArr);
			return response()->json();

		}else{
			$getId = Redis::get($user_id);
			$arr = unserialize($getId);
			unset($arr[$id]);
			$redisSet = Redis::set($user_id,serialize($arr));
			$getArr = Redis::get($user_id);
			$success = unserialize($getArr);
			return response()->json();
		}



	}
}
